package com.lik.javadeep.stack;

import java.util.Stack;

public class Parenthesis {
    public static void main(String[] args) {
        String str = "({[[]{}()]})";

        if (checkParenthesis(str)) {
            System.out.println("匹配");
        } else {
            System.out.println("失配");
        }
    }

    private static boolean checkParenthesis(String str) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {

            char currentChar = str.charAt(i);
            // 如果是左括号，入栈
            if (currentChar == '{' || currentChar == '[' || currentChar == '(') {
                stack.push(currentChar);
            }else if(stack.empty()){
                // 多出右括号的情况
                return false;
            } else if (currentChar == '}') {
                popIfMatch(stack, '{');
            } else if (currentChar == ']') {
                popIfMatch(stack, '[');
            } else if (currentChar == ')') {
                popIfMatch(stack, '(');
            }
        }

        return stack.empty();
    }

    /**
     * 在栈顶元素与目标元素匹配时，则进行pop操作
     *
     * @param stack      栈
     * @param exceptChar 目标元素
     * @return
     */
    private static void popIfMatch(Stack<Character> stack, char exceptChar) {
        if (stack.peek() == exceptChar) {
            stack.pop();
        }
    }
}
